<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="资产ID" prop="assetId">
        <el-input
          v-model="queryParams.assetId"
          placeholder="请输入资产ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="借用人" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入借用人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核结果" prop="auditResult">
        <el-select v-model="queryParams.auditResult" placeholder="请选择审核结果" clearable>
          <el-option label="通过" value="1" />
          <el-option label="拒绝" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable>
          <el-option label="已审核" value="1" />
          <el-option label="待审核" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['assets:brAudit:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="brAuditList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="审核ID" align="center" prop="borrowLogId" />
      <el-table-column label="资产ID" align="center" prop="assetId" width="180" />
      <el-table-column label="借用人" align="center" prop="userId">
        <template slot-scope="scope">
          <span>{{ userMap[scope.row.userId] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="借用时间" align="center" prop="borrowTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.borrowTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="借用地点" align="center" prop="borrowLocation" width="120" />

      <el-table-column label="审核人" align="center" prop="adminId">
        <template slot-scope="scope">
          <span>{{ userMap[scope.row.adminId] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核时间" align="center" prop="approveTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approveTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.auditStatus)"
                  :style="{ backgroundColor: getStatusType(scope.row.auditStatus), color: 'white' }"
          >
            {{ getStatusText(scope.row.auditStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核结果" align="center">
        <template slot-scope="scope">
          <el-tag
            :type="getAuditResultType(scope.row.auditResult)"
            :style="{ backgroundColor: getAuditResultColor(scope.row.auditResult), color: 'white' }"
          >
            {{ getAuditResultText(scope.row.auditResult) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--            v-hasPermi="['assets:brAudit:edit']"-->
<!--          >查看详情</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleApprove(scope.row)"
            v-hasPermi="['system:borrow:approve']"
            v-if="scope.row.auditStatus === 0"
          >审核</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="approveTitle" :visible.sync="approveDialogVisible" width="300px" append-to-body>
      <el-radio-group v-model="approveAction">
        <el-radio label="approve">通过</el-radio>
        <el-radio label="reject">拒绝</el-radio>
      </el-radio-group>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitApprove">确 定</el-button>
        <el-button @click="approveDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改借还审核对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBrAudit, getBrAudit, delBrAudit, addBrAudit, updateBrAudit } from "@/api/assets/brAudit";
import {parseTime} from "@/utils/ruoyi";
import {approveBorrow, rejectBorrow} from "@/api/assets/borrow";
import {listUser} from "@/api/system/user";

export default {
  name: "BrAudit",
  data() {
    return {
      //审核对话框变量
      approveDialogVisible: false,
      approveTitle: "",
      approveAction: "approve",
      approveBorrowLog: null, // 存储整个 borrowLog 对象
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 借还审核表格数据
      brAuditList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        assetId: null,
        userId: null,
        auditResult: null,
        auditStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        assetId: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        borrowTime: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        auditStatus: [
          { required: true, message: "$comment不能为空", trigger: "change" }
        ]
      },
      // 用户信息缓存
      userMap: {}
    };
  },
  created() {
    this.getList();
    this.getUserList(); // 获取用户信息并缓存
  },
  methods: {
    parseTime,
    /** 查询借还审核列表 */
    getList() {
      this.loading = true;
      listBrAudit(this.queryParams).then(response => {
        this.brAuditList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getUserList() {
      listUser().then(response => {
        this.userMap = response.rows.reduce((map, user) => {
          map[user.userId] = user.userName;
          return map;
        }, {});
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        borrowLogId: null,
        assetId: null,
        userId: null,
        borrowTime: null,
        returnTime: null,
        borrowLatitude: null,
        borrowLongitude: null,
        borrowAltitude: null,
        returnLatitude: null,
        returnLongitude: null,
        returnAltitude: null,
        borrowLocation: null,
        returnLocation: null,
        borrowReason: null,
        adminId: null,
        approveTime: null,
        auditResult: null,
        auditStatus: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.borrowLogId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加借还审核";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const borrowLogId = row.borrowLogId || this.ids
      getBrAudit(borrowLogId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改借还审核";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.borrowLogId != null) {
            updateBrAudit(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBrAudit(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const borrowLogIds = row.borrowLogId || this.ids;
      this.$modal.confirm('是否确认删除借还审核编号为"' + borrowLogIds + '"的数据项？').then(function() {
        return delBrAudit(borrowLogIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('BrAudit/brAudit/export', {
        ...this.queryParams
      }, `brAudit_${new Date().getTime()}.xlsx`)
    },
    // 新增 getAuditResultType 方法
    getAuditResultType(auditResult) {
      if (auditResult === 0) return 'danger'; // 拒绝
      if (auditResult === 1) return 'success'; // 通过
      return ''; // 默认返回空字符串
    },
    // 新增 getAuditResultColor 方法
    getAuditResultColor(auditResult) {
      if (auditResult === 0) return 'red'; // 拒绝
      if (auditResult === 1) return 'green'; // 通过
      return '#FFD700'; // 默认返回空字符串
    },
    // 新增 getAuditResultText 方法
    getAuditResultText(auditResult) {
      if (auditResult === 0) return '拒绝';
      if (auditResult === 1) return '通过';
      return '待审核'; // 默认返回空字符串
    },
    getStatusText(auditStatus) {
      switch (auditStatus) {
        case 0:
          return '待审核';
        case 1:
          return '已审核';
        default:
          return '未知状态';
      }
    },
    getStatusType(auditStatus) {
      switch (auditStatus) {
        case 0:
          return '#FFD700'; // 待审核状态使用黄色标签
        case 1:
          return 'green'; // 已审核状态使用绿色标签
        default:
          return 'info'; // 默认状态使用灰色标签
      }
    },
    /** 审核按钮操作 */
    handleApprove(row) {
      this.approveBorrowLog = { ...row }; // 复制整个 row 对象
      this.approveTitle = "审核编号为'" + row.borrowLogId + "'的借用请求";
      this.approveDialogVisible = true;
    },

    /** 提交审核操作 */
    submitApprove() {
      if (this.approveAction === "approve") {
        this.approveBorrowRequest(this.approveBorrowLog);
      } else if (this.approveAction === "reject") {
        this.rejectBorrowRequest(this.approveBorrowLog);
      }
      this.approveDialogVisible = false;
    },

    /** 审核通过操作 */
    approveBorrowRequest(borrowLog) {
      this.$modal.confirm('是否确认通过编号为"' + borrowLog.borrowLogId + '"的借用请求？').then(() => {
        approveBorrow(borrowLog).then(response => {
          this.$modal.msgSuccess("审核通过");
          this.getList();
        });
      }).catch(() => {});
    },

    /** 审核拒绝操作 */
    rejectBorrowRequest(borrowLog) {
      this.$modal.confirm('是否确认拒绝编号为"' + borrowLog.borrowLogId + '"的借用请求？').then(() => {
        rejectBorrow(borrowLog).then(response => {
          this.$modal.msgSuccess("审核拒绝");
          this.getList();
        });
      }).catch(() => {});
    },
  }
};
</script>
